import FormPcApi from "./api/FormApi";
import FormConstant from "./FormConstant";
import {Util} from "@lowcode/jpaas-common-lib";

var CustomQuery={};


CustomQuery.excuteQuery=function(customqueryAry, event, row,self_) {
  for(let i = 0, j = customqueryAry.length; i < j; i++) {
    var customquery = customqueryAry[i];
    var events = customquery.event;
    var isExcute = false;
    for(let m = 0, n = events.length; m < n; m++) {
      if(events[m] == event) {
        isExcute = true;
        break;
      }
    }
    if(!isExcute){
      return;
    }

    //isMain当前字段是主表还是子表
    var isMain = customquery.isMain;
    //查询参数数组
    var gridInput = customquery.gridInput;

    //绑定字段数组
    var gridReturn = customquery.gridReturn;
    //绑定字段是主表还是子表
    var gridName = customquery.gridName;
    var params = {};
    //组装查询参数
    params = CustomQuery.getParamsInput(gridInput,self_.data,row);

    var paramsStr = JSON.stringify(params);

    //自定义查询key;
    var customquery_key = customquery.customquery;

    if(paramsStr == '{}') {
        if(self_['customuery_'+customquery_key]){
            CustomQuery.bindRows([{}],gridName,gridReturn,isMain,row,self_,customquery,true);
        }
        continue;
    }

    FormPcApi.queryForJson(customquery_key, {
      params: JSON.stringify(params)
    }).then(res => {
      //获取的数据
      var rows = res.data;
      if(!(rows instanceof Array)) rows = [rows];

      self_['customuery_'+customquery_key]=true;
      CustomQuery.bindRows(rows,gridName,gridReturn,isMain,row,self_,customquery);
    })
  }
},
CustomQuery.bindRows=function(rows,gridName,gridReturn,isMain,row,self_,customquery,flag){
    var setTmpObj = {};
    var subAry = [];
    for(var i = 0; i < rows.length; i++) {
        var rtnTmp = rows[i];
        //子表对象
        var subObj = {};
        var value="";
        for(var k = 0, l = gridReturn.length; k < l; k++) {
            var item = gridReturn[k];
            var valmode=item.valmode;
            var bindField=item.bindField;

            if(valmode=="double"){
                var json={};
                json.label=rtnTmp[item.returnLabel.toUpperCase()];
                json.value=rtnTmp[item.returnValue.toUpperCase()];
                value= JSON.stringify(json) ;
            }else{
                value=rtnTmp[item.returnValue.toUpperCase()];
            }
            if(!bindField) {
                continue
            }
            //主表编辑按钮  绑定主表值
            if(isMain && gridName == 'main') {
                setTmpObj[bindField] = (i == 0) ? value : setTmpObj[bindField] + "," + value;
            } else if(isMain && gridName != 'main') { //主表编辑按钮  绑定子表值
                subObj[bindField] = value;
                subObj.index_=Util.randomId();
                subObj.selected=false;
            } else if(!isMain && gridName != 'main') { //子表编辑按钮  绑定子表行
                setTmpObj[bindField] = (i == 0) ? value : setTmpObj[bindField] + "," + value;
            }
        }
        //添加子表行
        subAry.push(subObj);
        //自定义按钮本身的值
    }
    if(gridName) {
        if(isMain && gridName == 'main') {
            for(var key in setTmpObj) {
                self_.$set(self_.data, key, setTmpObj[key])
            }
        } else if(isMain && gridName != 'main') { //主表编辑按钮  绑定子表值
            if(!subAry || subAry.length == 0) return;
            var grids = self_.data[FormConstant.SubPrefix + gridName];
            if(!grids || grids.length == 0) {
                grids = [];
            }
            var uniqueField=customquery.uniqueField;
            var canAdd=CustomQuery.canAddRow(uniqueField,subAry,grids);
            if(canAdd){
                grids = [];
                if(!flag){
                    if (customquery.isConcat) {
                        grids = grids.concat(subAry);
                    } else {
                        grids = subAry;
                    }
                }
                self_.$set(self_.data, FormConstant.SubPrefix + gridName, grids);
            }
        } else if(!isMain && gridName != 'main') { //子表编辑按钮  绑定子表行
            for(var key in setTmpObj) {
                row[key] = setTmpObj[key];
            }
        }
    }
},
//[{"field": "PARENT_CODE_","bindVal": "w","idx_": 1}]
CustomQuery.getParamsInput=function(gridInput,data,row) {
  if(!gridInput || gridInput.length == 0) return {};
  var param = {};
  for(let i = 0, j = gridInput.length; i < j; i++) {
    var obj = gridInput[i];
    var bindVal = obj.bindVal;
    var valmode = obj.valmode;
    var table = obj.table;
    var mode=obj.mappingMode;
    var val="";
    if(mode=="mapping"){
      val="main"==table?data[bindVal]:row[bindVal]
    }
    else{
      val= eval('(function() {' + bindVal + '}())');;
    }

    if(!val) { //父联动字段为空
      delete param[obj.field];
    } else {
      if(mode=="mapping"){
        if(valmode=="single"){
          param[obj.field]=val;
        }
        else{

          var json=JSON.parse(val)
          param[obj.field]=json.value;
        }
      }
      else{
        param[obj.field]=val;
      }
    }
  }
  return param;
};

CustomQuery.canAddRow=function(uniqueField,newRow,subTableData) {
  if(!uniqueField){
    return true;
  }
  var val=newRow[0][uniqueField];
  var ary= subTableData.filter(item=>{
    return item[uniqueField]==val;
  });
  if(ary.length==0){
    return true;
  }
  return false;
}



export  default  CustomQuery;
